package com.tiniplanet.webgate.security;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.tiniplanet.webgate.entity.Credential;
import com.tiniplanet.webgate.service.CredentialService;

public class CustomUserDetailsService implements UserDetailsService {
	protected static Logger logger = Logger
			.getLogger(CustomUserDetailsService.class);
	
	private ThreadLocal<User> currentUser = new ThreadLocal<User>();	
	
	@Autowired
	private CredentialService credentialService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		logger.debug("Check credential");
		Credential credential = credentialService.getByUsername(username);
		if (credential == null)
			throw new UsernameNotFoundException("user not found");

		User user = credentialService.getSecurityInstance(credential);
		currentUser.set(user);		
		return user;
	}
	
	
}
